from typing import List

from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import joinedload

from app.database.models import Order, User, VPNServer
from app.database.services.users import get_user


async def get_server(session: AsyncSession, server_id: int) -> VPNServer:

    q = select(VPNServer).where(VPNServer.id == server_id)

    res = await session.execute(q)

    return res.scalar()


async def get_free_vpn_server(session: AsyncSession, user: User) -> List[VPNServer]:

    q = (
        select(VPNServer)
        .filter(VPNServer.status == "active")
        .outerjoin(VPNServer.orders)
        .filter(Order.user != user)
    ).options(joinedload(VPNServer.orders))

    res = await session.execute(q)

    servers = res.scalars().unique().all()

    return [server for server in servers if len(server.orders) < 5]
